<template>
  <div style="margin-top: 20px">
    <el-row>
      <el-input v-model="input" placeholder="姓名/档案号" style="width: 300px"></el-input>&nbsp;
      <el-button
        icon="el-icon-search"
        type="primary"
        @click="search(input)"
      ></el-button>
      <el-button @click="addmember" type="warning" icon="el-icon-circle-plus-outline">新增</el-button>
      <el-button @click="quanxian" type="warning" >角色授予/收回</el-button>
    </el-row>
    <br/>
    <div>
      <el-table
        v-loading="loading"
        :data="tableData.slice((currentPage-1)*pageSize,currentPage*pageSize)"
        border
      >
        <el-table-column type="selection" width="55">
          <template slot-scope="scope">
            <el-checkbox v-model="scope.row.selected"></el-checkbox>
          </template>
        </el-table-column>
        <el-table-column
          fixed
          prop="account"
          label="用户名"
          width="150"
        >
        </el-table-column>
        <el-table-column
          prop="user_name"
          label="真实姓名"
          width="120"
        >
        </el-table-column>
        <el-table-column
          prop="gender"
          label="性别"
          width="120"
        >
        </el-table-column>
        <el-table-column
          prop="age"
          label="年龄"
          width="120"
        >
        </el-table-column>
        <el-table-column
          prop="telephone"
          label="电话"
          width="120"
        >
        </el-table-column>
        <el-table-column
          prop="e_mail"
          label="邮箱"
          width="300"
        >
        </el-table-column>
        <el-table-column
          prop="birthday"
          label="添加日期"
          width="120"
        >
        </el-table-column>
        <el-table-column
          fixed="right"
          label="操作"
          width="300"
        >
          <template v-slot="scope">
            <el-button @click="openAsync(scope.row)" type="warning" size="small" icon="el-icon-edit">编辑</el-button>
            <el-button @click="open(scope.row)" type="danger" size="small" icon="el-icon-delete">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage4"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="tableData.length"
      >
      </el-pagination>
    </div>
    <div>
      <el-dialog title="添加" :before-close="openUAdd" :visible.sync="dialogFormVisible">
        <el-form :inline="true" :model="form" class="demo-form-inline" style="flex: 1;">
          <el-form-item label="真实姓名" style="width: 45%;" class="custom-margin">
            <el-input v-model="addForm.user_name" style="margin-left: 5px;"
                      class="custom-input "
            ></el-input>
          </el-form-item>
          <el-form-item label="身份证" prop="password" style="width: 45%;" class="custom-margin">
            <el-input v-model="addForm.idcard" style="margin-left: 25px;" class="custom-input "></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email" style="width: 45%;" class="custom-margin">
            <el-input v-model="addForm.e_mail" style="margin-left: 30px;" class="custom-input "></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile" style="width: 45%;">
            <el-input v-model="addForm.telephone" style="margin-left: 25px;" class="custom-input "></el-input>
          </el-form-item>
          <el-form-item label="性别" prop="gender" style="width: 45%;">
            <el-select v-model="addForm.gender" style="margin-left: 30px;" class="custom-input" filterable>
              <el-option value="男">男</el-option>
              <el-option value="女">女</el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="角色" prop="healthManager" style="width: 45%;">
            <el-select v-model="addForm.role_id" style="margin-left: 40px;" class="custom-input" filterable>
              <el-option v-for="(option1, index) in option1" :key="index" :label="option1.label"
                         :value="option1.value" :disabled="option1.disabled" :class="{ 'disabled-option':
                             option1.disabled }"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="年龄" prop="age" style="width: 45%;">
            <el-input v-model="addForm.age" style="margin-left: 30px;" class="custom-input "></el-input>
          </el-form-item>
          <el-form-item label="备注" prop="desc">
            <el-input type="textarea" v-model="addForm.remark" style="width: 600px;
  height: 40px;"
            ></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="openUAdd()">取 消</el-button>
          <el-button type="primary" @click="openOk('添加成功');dialogFormVisible = false">确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <div>
      <el-dialog title="编 辑" :before-close="opensaves" :visible.sync="opensave">
        <el-tabs v-model="activeName" @tab-click="handleClick">
            <el-form :inline="true" :model="form" class="demo-form-inline" style="flex: 1;">
              <el-form-item label="真实姓名" style="width: 45%;" class="custom-margin">
                <el-input v-model="updatefrom.user_name" style="margin-left: 5px;"
                          class="custom-input "
                ></el-input>
              </el-form-item>
              <el-form-item label="身份证" prop="password" style="width: 45%;" class="custom-margin">
                <el-input v-model="updatefrom.idcard" style="margin-left: 25px;" class="custom-input "></el-input>
              </el-form-item>
              <el-form-item label="邮箱" prop="email" style="width: 45%;" class="custom-margin">
                <el-input v-model="updatefrom.e_mail" style="margin-left: 30px;" class="custom-input "></el-input>
              </el-form-item>
              <el-form-item label="手机号" prop="mobile" style="width: 45%;">
                <el-input v-model="updatefrom.telephone" style="margin-left: 25px;" class="custom-input "></el-input>
              </el-form-item>
              <el-form-item label="性别" prop="gender" style="width: 45%;">
                <el-select v-model="updatefrom.gender" style="margin-left: 30px;" class="custom-input" filterable>
                  <el-option value="男">男</el-option>
                  <el-option value="女">女</el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="年龄" prop="age" style="width: 45%;">
                <el-input v-model="updatefrom.age" style="margin-left: 40px;" class="custom-input "></el-input>
              </el-form-item>
              <el-form-item label="备注" prop="desc">
                <el-input type="textarea" v-model="updatefrom.remark" style="width: 600px;
  height: 40px;"
                ></el-input>
              </el-form-item>
            </el-form>
        </el-tabs>
        <div slot="footer" class="dialog-footer">
          <el-button @click="opensaves()">取 消</el-button>
          <el-button type="primary" @click="openOk('保存成功');opensave = false">保 存</el-button>
        </div>
      </el-dialog>
    </div>
    <div>
      <el-dialog title="授予/收回" :before-close="openquanxain" :visible.sync="openquanxain">
        <el-transfer
          filterable
          @change="handleChange"
          :filter-method="filterMethod"
          filter-placeholder="请输入城市拼音"
          :titles="['可以赋予的角色', '已有的角色']"
          :button-texts="['删除','添加']"
          v-model="value"
          :data="data">
        </el-transfer>
        <div slot="footer" class="dialog-footer">
          <el-button @click="openUAdd()">取 消</el-button>
          <el-button type="primary" @click="openOk('授予/收回成功');openquanxain = false">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>

import axios from 'axios'
import getters from '@/store/getters';

export default {
  beforeCreate() {
    //  console.log('beforeCreate: 页面加载前执行方法')
    axios.get('api/user/queryuser').then(res => {
      console.log(res)
      this.tableData1 = res.data.data
      this.tableData = res.data.data
      //   console.log(this.tableData.length)
    })
  },
  mounted() {
    this.totalNum = this.tableData.length
  },
  methods: {
    handleChange(newData, direction, movedKeys) {
      if (direction === 'right') {
        // 从左边转移到右边
        // 获取右边 Transfer 区域的 label 内容
        const labels = movedKeys.map(key => {
          const item = this.data.find(d => d.key === key);
          return item ? item.label : null;
        });
        console.log('右边的 label 内容：', labels);
        for(let i=0;i<labels.length;i++) {
          if (this.Del.length === 0) {
            this.add.push(labels[i])
          } else {
            const index = this.Del.indexOf(labels[i]);
            if (index !== -1) {
              // 如果包含，则将该元素从 Del 数组中删除
              this.Del.splice(index, 1);
            } else {
              // 如果不存在，则将该元素添加到 add 数组中
              this.add.push(labels[i]);
            }
          }
        }
      } else if (direction === 'left') {
        const labels = movedKeys.map(key => {
          const item = this.data.find(d => d.key === key);
          return item ? item.label : null;
        });
        console.log('左边的 label 内容：', labels);
        for (let i = 0; i < labels.length; i++) {
          if (this.add.length === 0) {
            this.Del.push(labels[i])
          } else {
            const index = this.add.indexOf(labels[i]);
            if (index !== -1) {
              // 如果包含，则将该元素从 Del 数组中删除
              this.add.splice(index, 1);
            } else {
              // 如果不存在，则将该元素添加到 add 数组中
              this.Del.push(labels[i]);
            }
          }
        }
      }
      console.log(this.Del);
      console.log(this.add);
    },
    generateData(cities) {
      const data = [];
      const pinyin = ['shanghai', 'beijing', 'guangzhou', 'shenzhen', 'nanjing', 'xian', 'chengdu'];
      cities.forEach((city, index) => {
        data.push({
          label: city,
          key: index,
          pinyin: pinyin[index]
        });
      });
      return data;
    },
    customColorMethod(percentage) {
      if (percentage < 30) {
        return '#909399'
      } else if (percentage < 70) {
        return '#e6a23c'
      } else {
        return '#67c23a'
      }
    },
    increase() {
      this.percentage += 10
      if (this.percentage > 100) {
        this.percentage = 100
      }
    },
    decrease() {
      this.percentage -= 10
      if (this.percentage < 0) {
        this.percentage = 0
      }
    },
    quanxian() {
      let bianliang;
      const permissions = getters.permissions(this.$store.state);
      permissions.forEach(permission => {
        const keyword = permission.keyword;
        if (keyword === "Role-Permission") {
          bianliang = 1;
        }
      });
      if(bianliang !== 1){
        alert("您没有权限");
        return;
      }
      this.value=[];
      this.cities=[];
      this.cities1=[];
      const selectedRows = this.tableData.filter(item => item.selected);
      const selectedIds = selectedRows.map(item => item.user_Id);
      this.checkbox=selectedIds;
      const user_id = getters.user_id(this.$store.state);
      const account = getters.account(this.$store.state);
      if(this.checkbox.length===0){
        alert("您没有选择任何用户");
        return;
      }
      if(this.checkbox.length!==1){
        alert("请选择一个用户");
        return;
      }
      for(let i=0;i<this.checkbox.length;i++){
        console.log(this.checkbox[i])
        if(user_id===this.checkbox[i]){
          alert("您不能修改自己的信息");
          return;
        }
      }
      console.log(this.checkbox)
      axios.post('api/user/rolename', {user_name:account}).then(res=>{
        res.data.data.forEach(item => {
          this.cities.push(item.name)
          this.cities1.push(item);
        });
        this.data = this.generateData(this.cities); // 更新数据
        this.$forceUpdate(); // 强制组件重新渲染
      })

      axios.post('api/user/rolename1', {user_Id:this.checkbox[0]}).then(res=>{
        let shuzu=[];
        res.data.data.forEach(item => {
          this.rooles1=item;
          shuzu.push(item.name)
        });
        console.log(shuzu)
        this.cities.forEach((city, index) => {
          console.log(city);
          for(let i=0;i<shuzu.length;i++){
            if(city===shuzu[i]){
              this.value.push(index)
              index-1;
            }
          }
        });
        console.log(res);
          });
      setTimeout(() => {
        this.openquanxain = true;
      }, 1000);
    },
    addmember() {
      this.option1 = [];
      let bianliang;
      console.log(getters)
      const permissions = getters.permissions(this.$store.state);
      console.log(permissions)
      permissions.forEach(permission => {
        const keyword = permission.keyword;
        if (keyword === "USER_ADD") {
          bianliang = 1;
        }
      });
      if (bianliang === 1) {
        axios.get("api/user/role").then((res) => {
          console.log(res);
          res.data.data.forEach((item) => {   // 使用 forEach() 遍历数组
            console.log(item.id, item.name);
            this.option1.push({"label": item.name, "value": item.id})
          })
        })
        this.dialogFormVisible = true;
      } else {
        alert("抱歉,您没有这个权限")
      }
    },
    search(bool) {

      this.currentPage = 1
      if (bool) {
        this.tableData = this.tableData1
        // 前端实现模糊查询--不用对接口
        let newListData = [] // 用于存放搜索出来数据的新数组
        if (this.input) {
          this.tableData.filter((item) => {
            if (item.user_name.indexOf(this.input) !== -1) {
              newListData.push(item)
            }
            else if (item.account.indexOf(this.input) !== -1) {
              newListData.push(item)
            }
          })
        }
        this.tableData = newListData
      } else {
        axios.get('api/user/queryuser').then(res => {
          console.log(res)
          this.tableData1 = res.data.data
          this.tableData = res.data.data
          //   console.log(this.tableData.length)
        })
      }
    },
    handleClick(row) {
      //console.log(row)
    },
    handleSizeChange(val) {
      this.pageSize = val
      //   console.log(`每页 ${val} 条`)
    },
    handleCurrentChange(val) {
      this.currentPage = val
      // console.log(`当前页: ${val}`)
    },
    handleSizeChanges(val) {
      this.pageSizes = val
      //  console.log(`每页 ${val} 条`)
    },
    handleCurrentChanges(val) {
      this.currentPages = val
      // console.log(`当前页: ${val}`)
    },
    //编辑查询
    openAsync(id) {
      this.option1 = [];
      let bianliang;
      const permissions = getters.permissions(this.$store.state);
      permissions.forEach(permission => {
        const keyword = permission.keyword;
        //   console.log(keyword)
        if (keyword === "USER_EDIT") {
          bianliang = 1;
        }
      });
      if (bianliang === 1) {
        axios.get("api/member/user").then((res) => {
          console.log(res);
          res.data.data.forEach((item) => {   // 使用 forEach() 遍历数组
            console.log(item.user_id, item.account);
            this.option1.push({"label": item.account, "value": item.user_id})
          })
        })
        this.updatefrom=id;
        this.opensave = true
      } else {
        alert("抱歉,您没有这个权限")
      }

    },
    open(id) {
      let bianliang;
      const permissions = getters.permissions(this.$store.state);
      permissions.forEach(permission => {
        const keyword = permission.keyword;
        //   console.log(keyword)
        if (keyword === "USER_DELETE") {
          bianliang = 1;
        }
      });
      if (bianliang === 1) {
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          axios.post('api/user/Deluser', id).then((res) => {
            if (res.data.code === '200') {
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
              axios.get('api/user/queryuser').then(res => {
                console.log(res)
                this.tableData1 = res.data.data
                this.tableData = res.data.data
                //   console.log(this.tableData.length)
              })
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      } else {
        alert("抱歉,您没有这个权限")
      }
    },
    Updates(id) {
      this.UpdateData = true
      let data = this.tableData.find((da) => da.name === id)
      this.updatefrom.name = data.name
    },
    openUpdate() {
      this.$confirm('是否退出修改?', '确认信息', {
        distinguishCancelAndClose: true,
        confirmButtonText: '取消',
        cancelButtonText: '退出'
      })
        .then(() => {
          this.$message({
            type: 'info',
            message: '放弃退出,继续修改'
          })
        })
        .catch(action => {
          this.$message({
            type: 'info',
            message: action === 'cancel'
              ? '放弃修改并离开页面'
              : '停留在当前页面'
          })
          if (action !== 'close') {
            this.UpdateData = false
          }
        })
    },
    openUAdd() {
      this.$confirm('是否退出添加?', '确认信息', {
        distinguishCancelAndClose: true,
        confirmButtonText: '取消',
        cancelButtonText: '退出'
      })
        .then(() => {
          this.$message({
            type: 'info',
            message: '放弃退出,继续添加'
          })
        })
        .catch(action => {
          this.$message({
            type: 'info',
            message: action === 'cancel'
              ? '放弃添加并离开页面'
              : '停留在当前页面'
          })
          if (action !== 'close') {
            this.dialogFormVisible = false
            this.openquanxain=false
          }
        })
    },
    opensaves() {
      this.$confirm('是否退出保存?', '确认信息', {
        distinguishCancelAndClose: true,
        confirmButtonText: '取消',
        cancelButtonText: '退出'
      })
        .then(() => {
          this.$message({
            type: 'info',
            message: '放弃退出'
          })
        })
        .catch(action => {
          this.$message({
            type: 'info',
            message: action === 'cancel'
              ? '放弃保存并离开页面'
              : '停留在当前页面'
          })
          if (action !== 'close') {
            this.opensave = false
          }
        })
    },
    openOk(val) {
      if(val === '授予/收回成功') {
        console.log(this.add)
        console.log(this.Del)
        console.log(this.cities1);
        const add1 = [];
        const Del1=[];
        this.cities1.some(item => {
          if (this.add.includes(item.name)) {
            add1.push(item.id);
          }
          if (this.Del.includes(item.name)) {
            Del1.push(item.id);
          }
        });
        console.log(add1);
        console.log(Del1);
        console.log(this.checkbox[0]);
        const  data={
          add:add1,
          del:Del1,
          ac_id: this.checkbox[0] // 示例
        }
        axios.post('api/user/quanxainfo', data)
          .then(response => {
            // 处理返回的结果
            console.log(response);
            if(response.data.code === '200') {
              this.$message({
                message: val,
                type: 'success'
              })
            }
          })
          .catch(error => {
            // 处理异常
            console.error('Error:', error);
          });
        this.add=[];
        this.Del=[];
      }
      if (val === '添加成功') {
        console.log(this.addForm)
        axios.post('api/user/adduser', this.addForm).then((res) => {
          //console.log(res.data.code)
          if (res.data.code === '200') {
            this.$message({
              message: val,
              type: 'success'
            })
            axios.get('api/user/queryuser').then(res => {
              console.log(res)
              this.tableData1 = res.data.data
              this.tableData = res.data.data
              //   console.log(this.tableData.length)
            })
          }
        })
      }
      if (val === '保存成功') {
         console.log(this.updatefrom)
        axios.post('api/user/updateuser', this.updatefrom,).then((res) => {
          if (res.data.code === '200') {
            this.$message({
              message: val,
              type: 'success'
            })
            axios.get('api/user/queryuser').then(res => {
              this.tableData1 = res.data.data
              this.tableData = res.data.data
            })
          }
        });
      }
    }
  },
  data() {
    return {
      percentage: 20,
      customColor: '#409eff',
      customColors: [
        {color: '#f56c6c', percentage: 20},
        {color: '#e6a23c', percentage: 40},
        {color: '#5cb87a', percentage: 60},
        {color: '#1989fa', percentage: 80},
        {color: '#6f7ad3', percentage: 100}
      ],
      cities1: [],
      cities: [],
      data: [],
      value: [],
      filterMethod(query, item) {
        return item.pinyin.indexOf(query) > -1;
      },
      add: [],
      Del: [],
      checkbox:[],
      checkList: [],
      option1: [],
      activeName: 'first',
      updatefrom: {
        user_Id:"",
        gender: "",
        user_name: "",
        age: "",
        remark:"",
        e_mail:"",
        telephone:"",
        address:"",
        idcard:"",
        role_id:"",
      },
      addForm: {
        gender: "",
        user_name: "",
        age: "",
        remark:"",
        e_mail:"",
        telephone:"",
        address:"",
        idcard:"",
        role_id:"",
      }
      ,
      opensave: false,
      UpdateData:
        false,
      openquanxain: false,
      form:
        '',
      dialogFormVisible:
        false,
      currentPage:
        1,
      input:
        '',
      pageSize:
        5,
      totalNum:
        10,
      currentPages:
        1,
      inputs:
        '',
      pageSizes:
        5,
      totalNums:
        10,
      tableData:
        [],
      tableData1:
        [],
      loading:
        false
    }
  }
}
</script>
<style>
.custom-input {
  width: 200px;
  height: 40px;
}

</style>
